const express = require('express')

const app = express()
const joi = require('joi')
const bodyparser = require('body-parser'); //body中间件
const cors = require('cors')
app.use(cors())
app.use(express.static('./public'));
app.use(express.static('./largeUpload'));
app.use(express.urlencoded({ extended: false }))
/* app.use(express.json()); */
app.use(bodyparser.json());
app.use((req, res, next) => {
    res.cc = function (err, status = 203) {
        res.send({
            status,
            msg: err instanceof Error ? err.message : err
        })
    }
    next()
})

const expressJwt = require('express-jwt')
const config = require('./config')
/* app.use(expressJwt({secret:config.jwtSecretKey})) */
app.use(
    expressJwt({
        secret: config.jwtSecretKey,
        getToken: function (req) {
            if (req.headers && (req.headers.authorization || req.headers.token)) {
                if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
                    // 如果是在 Authorization 请求头中使用 Bearer token 形式
                    return req.headers.authorization.split(' ')[1];
                } else if (req.headers.token) {
                    // 如果是在 token 请求头中直接使用 token 字段
                    return req.headers.token;
                }
            }
            return null;
        },
    }).unless({ path: ['/api/login'] })
);

const userRouter = require('./router/user')
app.use('/api', userRouter)
const systemRouter = require('./router/system')
app.use('/api', systemRouter)
const protableRouter=require('./router/proTableForm')
app.use('/api',protableRouter)
const dictorRouter=require('./router/richText')
app.use('/api',dictorRouter)
const largeFileRouter=require('./router/largeFileUpload')
app.use('/api',largeFileRouter)

app.use((err, req, res, next) => {
    if (err instanceof joi.ValidationError) return res.cc(err)
    if (err.name === 'UnauthorizedError') return res.cc('身份认证失败')
    res.contentType('text/html; charset=utf-8');
    res.cc(err)
})

app.listen(443, () => {
    console.log('api server running at http://127.0.0.1:443')
})